package com.tiennt.android.callnotes.activities;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SearchView;

import com.tiennt.android.callnotes.MainActivity;
import com.tiennt.android.callnotes.R;
import com.tiennt.android.callnotes.ViewNotesByContactActivity;
import com.tiennt.android.callnotes.models.contentholders.ContactInfo;
import com.tiennt.android.callnotes.models.listadapters.ListContactsAdapter;
import com.tiennt.android.callnotes.utils.ProjectUtils;

public class ContactsActivity extends Activity implements
		SearchView.OnQueryTextListener {
	private final String TAG = "ViewContactsActivity";
	private final boolean DBG = true;

	private ListView mListContacts;
	private ArrayList<ContactInfo> mContactsData;
	ListContactsAdapter mListContactsAdapter;
	ProgressBar mProgressBar;
	SearchView mSearchView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contacts);

		ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setTitle("Contact");
		mListContacts = (ListView) findViewById(R.id.lvContacts);
		setupListView(mListContacts);

		mProgressBar = (ProgressBar) findViewById(R.id.progrees);

		new GetContactAsyncTask().execute();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.contacts, menu);

		MenuItem searchItem = menu.findItem(R.id.action_search);
		mSearchView = (SearchView) searchItem.getActionView();
		mSearchView.setQueryHint("Contact..");

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			// app icon in Action Bar clicked; go home
			Intent intent = new Intent(this, MainActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void setupListView(ListView lv) {
		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				doListItemClick(parent, view, position, id);
			}

		});
	}

	private void doListItemClick(AdapterView<?> parent, View view,
			int position, long id) {
		ContactInfo contactInfo = mListContactsAdapter.getItem(position);
		Bundle bundle = new Bundle();
		bundle.putLong(ProjectUtils.BUNDLEKEY_CONTACTID,
				contactInfo.getContactId());
		bundle.putString(ProjectUtils.BUNDLEKEY_CONTACTNAME,
				contactInfo.getContactName());
		ByteArrayOutputStream bs = new ByteArrayOutputStream();
		contactInfo.getContactPhoto().compress(Bitmap.CompressFormat.PNG, 100,
				bs);

		Intent iNotesByContact = new Intent(this,
				ViewNotesByContactActivity.class);
		iNotesByContact.putExtras(bundle);
		iNotesByContact.putExtra(ProjectUtils.BUNDLEKEY_CONTACTPHOTO,
				bs.toByteArray());
		startActivity(iNotesByContact);
	}

	public class GetContactAsyncTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			mProgressBar.setVisibility(View.GONE);
			mListContacts.setVisibility(View.VISIBLE);
			mListContactsAdapter = new ListContactsAdapter(
					ContactsActivity.this, R.layout.list_contacts_row,
					mContactsData);
			mListContacts.setAdapter(mListContactsAdapter);
			mSearchView.setOnQueryTextListener(ContactsActivity.this);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			mContactsData = getAllContacts();
			return null;
		}

	}

	private ArrayList<ContactInfo> getAllContacts() {
		ArrayList<ContactInfo> result = new ArrayList<ContactInfo>();

		Bitmap defaultPhoto = BitmapFactory.decodeResource(getResources(),
				R.drawable.contact_image2);

		Cursor cursor = this.getContentResolver().query(
				ContactsContract.Contacts.CONTENT_URI,
				new String[] { ContactsContract.Contacts._ID,
						ContactsContract.Contacts.DISPLAY_NAME,
						ContactsContract.Contacts.HAS_PHONE_NUMBER }, null,
				null, ContactsContract.Contacts.DISPLAY_NAME);
		if (cursor != null && cursor.moveToFirst()) {
			do {
				int hasPhoneNum = cursor
						.getInt(cursor
								.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

				if (hasPhoneNum == 0) {
					continue;
				}
				ContactInfo contactInfo = new ContactInfo();

				long contactId = cursor.getLong(cursor
						.getColumnIndex(ContactsContract.Contacts._ID));

				contactInfo.setContactId(contactId);
				contactInfo
						.setContactName(cursor.getString(cursor
								.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));

				Bitmap photo = defaultPhoto;

				try {
					InputStream inputStream = ContactsContract.Contacts
							.openContactPhotoInputStream(
									this.getContentResolver(),
									ContentUris
											.withAppendedId(
													ContactsContract.Contacts.CONTENT_URI,
													contactId));

					if (inputStream != null) {
						photo = BitmapFactory.decodeStream(inputStream);
						inputStream.close();
					}

				} catch (IOException e) {
					e.printStackTrace();
				}
				contactInfo.setContactPhoto(photo);
				result.add(contactInfo);
			} while (cursor.moveToNext());
		}
		cursor.close();
		return result;
	}

	public void log(String msg) {
		if (DBG) {
			Log.d(TAG, msg);
		}
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		// TODO Auto-generated method stub
		mListContactsAdapter.getFilter().filter(newText);
		return true;
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		// TODO Auto-generated method stub
		return false;
	}
}
